#!/usr/bin/env python
#-*- coding:utf-8 -*-

from django.utils.safestring import mark_safe
from django.http.request import QueryDict


class Pagination:
    def __init__(self,page,all_count,params=None,per_num=10,max_show=11):
        try:
            self.page = int(page)
            if self.page <= 0:
                self.page = 1
        except Exception:
            self.page = 1
            # 每页显示的个数
        #查询条件
        self.params=params
        if not self.params:
            self.params=QueryDict(mutable=True)   #可编辑
        start = (self.page - 1) * per_num
        end = (self.page) * per_num
        # 总页码
        all_count = all_count
        total_num, more = divmod(all_count, per_num)
        if more:
            total_num += 1

            # 要显示的页码数
        half_show = max_show // 2
        if total_num <= max_show:
            page_start = 1
            page_end = total_num
        else:
            if self.page - half_show <= 0:
                # 页码的起始值
                page_start = 1
                # 页码的终止值
                page_end = max_show
            elif self.page + half_show > total_num:
                page_end = total_num
                page_start = total_num - max_show + 1

            else:
                # 页码的起始值
                page_start = self.page - half_show
                # 页码的终止值
                page_end = self.page + half_show
        self.page_start = page_start
        self.page_end = page_end
        self.total_num = total_num
        self.start = (self.page - 1) * per_num
        self.end = self.page * per_num
    @property
    def page_html(self):
        li_list = []
        if self.page == 1:
            li_list.append('<li class="disabled"><span aria-hidden="true">&laquo;</span></a></li>')
        else:
            self.params['page']=self.page-1  # { query:13 ,page : 1 }
            li_list.append(
                '<li><a href="?{}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span></a></li>'.format(
                    self.params.urlencode()))  #?query=1&page=2
        for i in range(self.page_start, self.page_end + 1):
            self.params['page']=i
            if i == self.page:
                li_list.append(' <li class="active"><a href="?{}">{}</a></li>'.format(self.params.urlencode(), i))
            else:
                li_list.append(' <li><a href="?{}">{}</a></li>'.format(self.params.urlencode(), i))
        if self.page == self.total_num:
            li_list.append('<li class="active"><span aria-hidden="true">&raquo;</span></a></li>')
        else:
            self.params['page'] = self.page + 1
            li_list.append(
                '<li><a href="?{}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'.format(
                    self.params.urlencode()))

        page_html = ''.join(li_list)
        return mark_safe(''.join(li_list))
